package online.heycm.codegenerator.common.jdbc;

import cn.hutool.core.exceptions.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import online.heycm.codegenerator.common.types.DBType;
import online.heycm.codegenerator.service.param.ConnectReq;
import online.heycm.platform.common.entity.exception.Assert;
import online.heycm.platform.common.entity.exception.BizException;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author hey
 * @version 1.0
 * @date 2023/12/21 10:29
 */
@Slf4j
public class Jdbc {

    private static final String SHOW_TABLE_SQL = "SHOW TABLES";

    public static Connection getConnection(String driver, String url, String username, String password) {
        try {
            Class.forName(driver);
            DriverManager.setLoginTimeout(5);
            return DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            log.error("获取数据库连接发生异常: {}", url, e);
            throw new BizException("获取数据库连接失败: " + e.getMessage());
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public static void close(Connection connection) {
        try {
            if (connection == null || connection.isClosed()) {
                return;
            }
            connection.close();
        } catch (SQLException e) {
            log.error("Connection 关闭异常: {}", e.getMessage(), e);
        }
    }

    public static List<String> showTables(Connection connection) {
        Assert.notNull(connection, "Connection is invalid");
        List<String> tables = new ArrayList<>();
        PreparedStatement statement = null;
        ResultSet result = null;
        try {
            statement = connection.prepareStatement(SHOW_TABLE_SQL);
            result = statement.executeQuery();
            while (result.next()) {
                tables.add(result.getString(1));
            }
        } catch (SQLException e) {
            log.error("SQL 执行异常: {}", e.getMessage(), e);
            throw new BizException("查询数据表失败");
        } finally {
            try {
                if (result != null && !result.isClosed()) {
                    result.close();
                }
            } catch (SQLException e) {
                log.error("ResultSet 关闭异常: {}", e.getMessage(), e);
            }
            try {
                if (statement != null && !statement.isClosed()) {
                    statement.close();
                }
            } catch (SQLException e) {
                log.error("PreparedStatement 关闭异常: {}", e.getMessage(), e);
            }
        }
        return tables;
    }

}
